import React, {useEffect, useState} from 'react';
import {Input, Spin, Tree, Dropdown, Menu} from 'antd';
import {vehicleTree, locationLatest} from '@/pages/monitor/center/service'
import styles from './VehicleTree.less'
import VehicleTreeEvent from './VehicleTreeEvent'
import { message } from 'antd';

const {Search} = Input;

const VehicleTree = (
  {
    onTreeSelect,
    onTreeCheck,
    onTreeRightClick
  }
) => {
  const [vehicleTreeData, setVehicleTreeData] = useState([]);
  const [rightMenuData, setRightMenuData] = useState([]);
  const [menuVisible, setMenuVisible] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });


  const loadVehicleTreeData = () => {
    vehicleTree().then(res => {
      setVehicleTreeData(res ? buildVehicleTreeData([res]) : [])
    })
  }

  // 处理菜单数据,转换成Tree需要的数据结构
  const buildVehicleTreeData = items => {
    if (!items) {
      return []
    }
    return items.map((item, i) => {
      const result = {
        title: item.name,
        key: item.id,
        value: item.id,
        children: [],
      };
      result.children = buildVehicleTreeData(item.children);
      return result
    })
  }

  useEffect(() => {
    loadVehicleTreeData()
  }, []);

  const onSelect = (selected, node) => {
    onTreeSelect(selected, node)
  }

  const onRightClick = (e) => {
    e.event.preventDefault();
    setRightMenuData(
      [
        { label: '点名',      cmd: 'cmd001', code: e.node.key, key: e.node.key },
        { label: '拍照',      cmd: 'cmd002', code: e.node.key, key: e.node.key },
        { label: '发送消息',   cmd: 'cmd003', code: e.node.key, key: e.node.key },
        { label: '历史轨迹',   cmd: 'cmd004', code: e.node.key, key: e.node.key },
        { label: '电子围栏',   cmd: 'cmd005', code: e.node.key, key: e.node.key },
      ]
    );
    setMenuPosition({ x: e.event.clientX, y: e.event.clientY });
    setMenuVisible(true);
  }
  const handleCloseMenu = () => {
    setMenuVisible(false);
  };

  return (
    <div className={styles.container}>
      <Search
        style={{
          padding: '8px'
        }}
        placeholder="Search"
      />
      {
        vehicleTreeData.length > 0 &&
        <Tree
          defaultExpandAll
          treeData={vehicleTreeData}
          onSelect={onSelect}
          onCheck={onTreeCheck}
          onRightClick={onRightClick}
          checkable
          style={{
            paddingLeft: '8px'
          }}
        />
      }

      {menuVisible && (
        <div
          style={{
            position: "fixed",
            left: menuPosition.x,
            top: menuPosition.y,
            zIndex: 99999999,
            boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
          }}
          onClick={handleCloseMenu}
        >
          <Menu items={rightMenuData} onClick={(e) => onTreeRightClick(e.item.props)}  />
        </div>
      )}
    </div>
  );
}
export default VehicleTree;
